import React, { memo, useEffect, useState, useRef } from 'react';

import {
  Form,
  Input,
  Select,
  Table,
  Modal,
  DatePicker,
  Space,
  Popconfirm,
} from 'antd';
import { ProToolBar } from '@/base-ui';
import http from '@/services/request';

import { FormColumns } from './config';
import DivWrapper from './style';
import { IToolButton } from '@/base-ui/tool-bar';

//form
const NewForm = (props: any) => {
  const { houseList, form } = props;
  return (
    <Form form={form} ref={props.newref} layout={'vertical'}>
      <Form.Item
        label="请选择鸡舍"
        name="chickenHouseId"
        rules={[{ required: true, message: '请选择鸡舍' }]}
      >
        <Select style={{ width: 120 }} options={houseList} />
      </Form.Item>
      <Form.Item name="drugName" label="药品名称">
        <Input width={300} />
      </Form.Item>
      <Form.Item label="药品编号" name="drugNumber">
        <Input width={300} />
      </Form.Item>
      <Form.Item label="用药方式" name="way">
        <Input width={300} />
      </Form.Item>
      <Form.Item name="personInChargeName" label="负责员工名称">
        <Input width={300} />
      </Form.Item>
      <Form.Item label="负责人联系电话" name="personInChargePhone">
        <Input width={300} />
      </Form.Item>
      <Form.Item
        label="用药时间"
        name="druggingTime"
      >
        <DatePicker />
      </Form.Item>
    </Form>
  );
};

const GetUseManage = memo(() => {
  const [dataSource, setdataSource]: any = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [edited, setEdited]: any = useState('');
  const newref: any = useRef();
  const [houseList, setHouseList] = useState([]);
  const [houseMap, setHouseMap] = useState(new Map());
  const [form] = Form.useForm();
  const buttonGroup: IToolButton[] = [
    {
      type: 'create',
      text: '新增日志',
      isShow: true,
      onClick: () => {
        setAddModalVisible(true);
      },
      id: 9
    }
  ];
  const ForumColum = [
    ...FormColumns,
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record) => (
        <Space>
          <a onClick={() => openEditModal(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => deleteItem(record.id)}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const deleteItem = (id) => {
    http.delete(`/feed/druggingRecordFarming/delete/${id}`).then(() => {
      http.get('/feed/druggingRecordFarming/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  const openEditModal = (item) => {
    setEdited(item);
    setAddModalVisible(true);
    const { druggingTime, ...rest } = item;
    form.setFieldsValue(rest);
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      newedited.druggingTime &&
        (newedited.druggingTime = newedited.druggingTime.toJSON());
      http
        .put(`/feed/druggingRecordFarming/update`, {
          id: edited.id,
          ...newedited
        })
        .then(() => {
          http.get('/feed/druggingRecordFarming/list/1/10').then((res) => {
            setdataSource(res.data.records);
          });
        });
      setEdited(null);
      return;
    }

    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    addData.druggingTime &&
      (addData.druggingTime = addData.druggingTime.toJSON());
    const {
      chickenHouseId,
      drugName,
      drugNumber,
      way,
      personInChargeName,
      personInChargePhone,
      druggingTime
    } = addData;

    http
      .post('/feed/druggingRecordFarming/save', {
        chickenHouseId,
      drugName,
      drugNumber,
      way,
      personInChargeName,
      personInChargePhone,
      druggingTime
      })
      .then(() => {
        http.get('/feed/druggingRecordFarming/list/1/10').then((res) => {
          setdataSource(res.data.records);
        });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
    setEdited(false);
    form.resetFields();
  };

  useEffect(() => {
    http.get('/feed/druggingRecordFarming/list/1/10').then((res) => {
      setdataSource(res.data.records);
    });
    http.get('/feed/chicken/chickenHouseFarming/findAll').then((res) => {
      const list = res.data?.map((item) => {
        return { value: item.chickenHouseId, label: item.chickenHouseName };
      });
      const map = new Map();
      res.data?.forEach((item) => {
        map.set(item.chickenHouseId, item);
      });
      setHouseMap(map);
      setHouseList(list);
    });
  }, []);

  return (
    <DivWrapper>
      <ProToolBar buttonGroup={buttonGroup} />
      <Table
        dataSource={dataSource}
        columns={ForumColum}
        scroll={{ x: 1300 }}
      />
      <Modal
        width={'800px'}
        title="新增记录"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
        centered
      >
        <NewForm
          newref={newref}
          houseList={houseList}
          houseMap={houseMap}
          form={form}
        />
      </Modal>
    </DivWrapper>
  );
});

export default GetUseManage;
